<template>
    <div class="compare-page">
        <!-- 顶部 Header -->
        <header class="compare-header">
            <el-button type="text" :icon="ArrowLeft" @click="goBack">返回</el-button>
            <div class="header-right">
                <span class="similarity">
                    文本相似度：
                    <b class="similarity-badge">{{ similarity }}%</b>
                </span>
                <div class="connection-controls">
                     <span class="connection-control-title">连线调整:</span>
                     <div class="connection-control-buttons">
                         <el-button size="small" @click="adjustConnectionOffset('left', -5)" title="左侧连接点向左移动">←L</el-button>
                         <el-button size="small" @click="adjustConnectionOffset('left', 5)" title="左侧连接点向右移动">L→</el-button>
                         <el-button size="small" @click="adjustConnectionOffset('right', -5)" title="右侧连接点向左移动">←R</el-button>
                         <el-button size="small" @click="adjustConnectionOffset('right', 5)" title="右侧连接点向右移动">R→</el-button>
                         <el-button size="small" type="info" @click="resetConnectionOffset()" title="重置连线位置">重置</el-button>
                     </div>
                 </div>
                <el-button type="primary" :icon="Reading" @click="showDiffPoint">差异点</el-button>
            </div>
        </header>

        <!-- 中部 PDF 对比区 + 差异列表 -->
        <div class="compare-main">
            <div class="pdf-compare-content" :class="{ 'with-diff-list': showDiffList }">
                <div class="pdf-viewer">
                    <canvas ref="pdfCanvas" class="pdf-canvas pdf-canvas-full"></canvas>
                </div>
                <div class="page-control-panel">
                    <div class="footer-page footer-page-center" :style="{
                        position: 'absolute',
                        top: '45px',
                        left: '50%',
                        transform: 'translate(-50%, -100%)',
                        zIndex: 10
                    }">
                        <span class="page-current">{{ page1 }}</span>
                        <span class="page-sep">/</span>
                        <span class="page-total">{{ pdf1TotalPages }}</span>
                    </div>
                    <div class="page-control-btns mt-1">
                        <el-button size="default" :icon="ArrowLeft" @click="prevPage" class="page-arrow-btn"
                            :disabled="page1 <= 1 || page2 <= 1" />
                        <el-button size="default" :icon="ArrowRight" @click="nextPage" class="page-arrow-btn"
                            :disabled="page1 >= pdf1TotalPages || page2 >= pdf2TotalPages">
                        </el-button>
                    </div>
                </div>
                <div class="pdf-viewer">
                    <canvas ref="pdfCanvas2" class="pdf-canvas pdf-canvas-full"></canvas>
                </div>
            </div>
            <el-drawer
                v-model="showDiffList"
                title="差异列表"
                direction="rtl"
                size="340px"
                :with-header="true"
                :close-on-click-modal="true"
                :modal="false"
                custom-class="diff-list-drawer"
            >
                <div>
                    <div v-for="(item, idx) in diffList" :key="idx" class="diff-item diff-item-hover"
                        @click="highlightDiff(idx)">
                        <div class="diff-title">{{ item.type }}</div>
                        <div class="diff-row">
                            <span class="diff-label">左：</span>
                            <span class="text-red-500">{{ item.details.text.document1 }}</span>
                        </div>
                        <div class="diff-row">
                            <span class="diff-label">右：</span>
                            <span class="text-white">{{ item.details.text.document2 }}</span>
                        </div>
                    </div>
                </div>
            </el-drawer>
        </div>

        <!-- 底部 文件名和翻页 -->
        <footer class="compare-footer" :class="{ 'with-diff-list': showDiffList }">
            <div class="footer-block">
                <span class="footer-filename">{{ pdf1Name }}</span>
                <span class="footer-page">
                    <span class="page-current">{{ page1 }}</span>
                    <span class="page-sep">/</span>
                    <span class="page-total">{{ pdf1TotalPages }}</span>
                </span>
            </div>
            <div class="footer-block">
                <span class="footer-filename">{{ pdf2Name }}</span>
                <span class="footer-page">
                    <span class="page-current">{{ page2 }}</span>
                    <span class="page-sep">/</span>
                    <span class="page-total">{{ pdf2TotalPages }}</span>
                </span>
            </div>
        </footer>
    </div>
</template>

<script setup>

import { Reading, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import * as pdfjsLib from 'pdfjs-dist/build/pdf.min.mjs'

pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
    'pdfjs-dist/build/pdf.worker.mjs',
    import.meta.url
).toString()


import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute();
console.log(`route.params.res`, route.params); // 0


const similarity = ref(87)
const pdf1Url = ref('')
const pdf2Url = ref('')
const pdf1Name = 'document3.pdf'
const pdf2Name = 'document4.pdf'
const page1 = ref(1)
const page2 = ref(1)
const pdf1TotalPages = ref(1)
const pdf2TotalPages = ref(1)
const showDiffList = ref(false)

const pdfCanvas = ref(null)
const pdfCanvas2 = ref(null)

let pdf1Instance = null
let pdf2Instance = null
let pdf1RenderPromise = Promise.resolve();
let pdf2RenderPromise = Promise.resolve();

const diffList = ref([]) // 初始为空
// 连线位置偏移量 - 设置初始值使连线准确连接到文字差异
// 左侧文档连接点在右边界，右侧文档连接点在左边界
const connectionOffset = ref({ left: 5, right: -5 })

/**
 * 调整连线偏移量
 * @param {string} side 'left' 或 'right'
 * @param {number} value 偏移量增减值
 */
function adjustConnectionOffset(side, value) {
    if (side === 'left') {
        connectionOffset.value.left += value;
    } else {
        connectionOffset.value.right += value;
    }
    console.log(`当前连线偏移量: 左侧=${connectionOffset.value.left}, 右侧=${connectionOffset.value.right}`);
    
    // 重新绘制连线
    if (currentDiffIdx !== null) {
        highlightDiff(currentDiffIdx);
    }
}

/**
 * 重置连线偏移量到默认值
 */
function resetConnectionOffset() {
    // 根据屏幕宽度自动调整偏移量
    autoAdjustConnectionOffset();
    
    // 重新绘制连线
    if (currentDiffIdx !== null) {
        highlightDiff(currentDiffIdx);
    }
}

// 在翻页后自动高亮
watch([page1, page2], () => {
    // highlightDiffsForCurrentPage();
});

const showDiffPoint = () => {
    showDiffList.value = !showDiffList.value
}



// 修改loadAndRenderPdf，支持缓存pdf实例
async function loadAndRenderPdf(pageNum = 1) {
    if (!pdf1Instance) return;
    await pdf1RenderPromise;
    const page = await pdf1Instance.getPage(pageNum);
    const dpr = window.devicePixelRatio || 1;
    const viewport = page.getViewport({ scale: 1.5 });
    const canvas = pdfCanvas.value;
    const context = canvas.getContext('2d');
    canvas.width = viewport.width * dpr;
    canvas.height = viewport.height * dpr;
    canvas.style.width = `${viewport.width}px`;
    canvas.style.height = `${viewport.height}px`;
    context.setTransform(dpr, 0, 0, dpr, 0, 0);
    pdf1RenderPromise = page.render({
        canvasContext: context,
        viewport: viewport
    }).promise;
    await pdf1RenderPromise;
}

// 右侧PDF渲染，缓存pdf实例
async function loadAndRenderPdf2(pageNum = 1) {
    if (!pdf2Instance) return;
    await pdf2RenderPromise;
    const page = await pdf2Instance.getPage(pageNum);
    const dpr = window.devicePixelRatio || 1;
    const viewport = page.getViewport({ scale: 1.5 });
    const canvas = pdfCanvas2.value;
    const context = canvas.getContext('2d');
    canvas.width = viewport.width * dpr;
    canvas.height = viewport.height * dpr;
    canvas.style.width = `${viewport.width}px`;
    canvas.style.height = `${viewport.height}px`;
    context.setTransform(dpr, 0, 0, dpr, 0, 0);
    pdf2RenderPromise = page.render({
        canvasContext: context,
        viewport: viewport
    }).promise;
    await pdf2RenderPromise;
}

// 翻页按钮事件
function prevPage() {
    if (page1.value > 1) {
        page1.value--
        loadAndRenderPdf(page1.value)
    }
    if (page2.value > 1) {
        page2.value--
        loadAndRenderPdf2(page2.value)
    }
}

function nextPage() {
    if (page1.value < pdf1TotalPages.value) {
        page1.value++
        loadAndRenderPdf(page1.value)
    }
    if (page2.value < pdf2TotalPages.value) {
        page2.value++
        loadAndRenderPdf2(page2.value)
    }
}




function goBack() {
    router.push('/home')
}


let currentDiffIdx = null;
async function highlightDiff(idx) {
    currentDiffIdx = idx;
    const diff = diffList.value[idx];

    // 1. 获取页码信息
    const leftPage = diff.pageNumber || 1;
    const rightPage = diff.pageNumber || 1;

    // 2. 翻页（如果需要），并等待渲染
    if (page1.value !== leftPage) {
        await loadAndRenderPdf(leftPage);
        page1.value = leftPage;
    }
    if (page2.value !== rightPage) {
        await loadAndRenderPdf2(rightPage);
        page2.value = rightPage;
    }

    // 3. 使用JSON中的rectangleDoc1和rectangleDoc2坐标数据
    let leftHighlight = null;
    let rightHighlight = null;
    
    if (diff.details.rectangleDoc1) {
        const rect1 = diff.details.rectangleDoc1;
        // 调整y坐标计算，确保更准确地定位到文字位置
        // PDF坐标系（左下角为原点）转换为Canvas坐标系（左上角为原点）
        // 计算更精确的y坐标，考虑到PDF文字通常在矩形框的下部
        // 对于中文字符，通常基线位置更接近矩形框的下部
        // 根据实际测试结果调整偏移量
        const yOffset = rect1.height * 0.3; // 增加偏移量，使连线更接近文字中心
        leftHighlight = {
            pixelHeight: rect1.pixelHeight,
            pixelX: rect1.pixelX,
            pixelWidth: rect1.pixelWidth,
            pixelPageHeight: rect1.pixelPageHeight,
            pageHeight: rect1.pageHeight,
            pixelY: rect1.pixelY,
            x: rect1.x,
            y: rect1.pageHeight - rect1.y - rect1.height + yOffset, // 基本转换后向上偏移
            width: rect1.width,
            height: rect1.height,
            scale: 1.5,
            viewportHeight: rect1.pageHeight,
            originalY: rect1.y, // 保存原始y坐标，用于调试
            originalHeight: rect1.height, // 保存原始高度，用于调试
            yOffset: yOffset // 保存y偏移量，用于调试
        };
    }
    
    if (diff.details.rectangleDoc2) {
        const rect2 = diff.details.rectangleDoc2;
        // 调整y坐标计算，确保更准确地定位到文字位置
        // PDF坐标系（左下角为原点）转换为Canvas坐标系（左上角为原点）
        // 计算更精确的y坐标，考虑到PDF文字通常在矩形框的下部
        // 对于中文字符，通常基线位置更接近矩形框的下部
        // 根据实际测试结果调整偏移量
        const yOffset = rect2.height * 0.3; // 增加偏移量，使连线更接近文字中心
        rightHighlight = {
            pixelHeight: rect2.pixelHeight,
            pixelX: rect2.pixelX,
            pixelWidth: rect2.pixelWidth,
            pixelPageHeight: rect2.pixelPageHeight,
            pageHeight: rect2.pageHeight,
            pixelY: rect2.pixelY,
            x: rect2.x,
            y: rect2.pageHeight - rect2.y - rect2.height + yOffset, // 基本转换后向上偏移
            width: rect2.width,
            height: rect2.height,
            scale: 1.5,
            viewportHeight: rect2.pageHeight,
            originalY: rect2.y, // 保存原始y坐标，用于调试
            originalHeight: rect2.height, // 保存原始高度，用于调试
            yOffset: yOffset // 保存y偏移量，用于调试
        };
    }

    if ((leftHighlight && leftHighlight.x != null) || (rightHighlight && rightHighlight.x != null)) {
        // 输出调试信息，帮助分析连线位置
        console.log('高亮区域信息:', {
            left: leftHighlight,
            right: rightHighlight
        });
        
        // 4. 画连线
        setTimeout(() => {
            // drawDiffLine(leftHighlight, rightHighlight);
            // 输出连线后的调试信息
            console.log('连线已绘制，当前差异索引:', idx);
        }, 100);
    } else {
        // 清除连线
        const lineCanvas = document.getElementById('diff-line-canvas');
        if (lineCanvas) lineCanvas.getContext('2d').clearRect(0, 0, lineCanvas.width, lineCanvas.height);
    }
}

/**
 * 根据传入的 x, y, width, height 参数，对左右两个差异文本进行连线处理，中间用一个小方块图标连接
 * @param {Object} leftHighlight {x, y, width, height, scale, viewportHeight} 左侧高亮区域参数
 * @param {Object} rightHighlight {x, y, width, height, scale, viewportHeight} 右侧高亮区域参数
 */
function drawDiffLine(leftHighlight, rightHighlight) {
    // 创建或获取画布
    let lineCanvas = document.getElementById('diff-line-canvas');
    if (!lineCanvas) {
        lineCanvas = document.createElement('canvas');
        lineCanvas.id = 'diff-line-canvas';
        lineCanvas.style.position = 'fixed';
        lineCanvas.style.left = '0';
        lineCanvas.style.top = '0';
        lineCanvas.style.pointerEvents = 'none';
        lineCanvas.style.zIndex = 1000;
        document.body.appendChild(lineCanvas);
    }
    
    // 设置画布尺寸
    lineCanvas.width = window.innerWidth;
    lineCanvas.height = window.innerHeight;
    const ctx = lineCanvas.getContext('2d');
    ctx.clearRect(0, 0, lineCanvas.width, lineCanvas.height);
    
    // 获取左右PDF画布位置
    const leftCanvas = pdfCanvas.value;
    const rightCanvas = pdfCanvas2.value;
    const leftRect = leftCanvas?.getBoundingClientRect();
    const rightRect = rightCanvas?.getBoundingClientRect();
    
    // 计算连接点
    const leftPoint = convertPdfToScreenCoords(leftHighlight, leftRect, 'left');
    const rightPoint = convertPdfToScreenCoords(rightHighlight, rightRect, 'right');
    
    if (leftPoint && rightPoint) {
        // 绘制贝塞尔曲线连线
        ctx.beginPath();
        ctx.strokeStyle = 'rgba(64, 158, 255, 0.8)';
        ctx.lineWidth = 2;
        ctx.shadowColor = 'rgba(64, 158, 255, 0.4)';
        ctx.shadowBlur = 6;
        
        // 计算控制点
        const horizontalDistance = rightPoint.x - leftPoint.x;
        const controlPointOffset = horizontalDistance * 0.3;
        
        ctx.moveTo(leftPoint.x, leftPoint.y);
        ctx.bezierCurveTo(
            leftPoint.x + controlPointOffset, leftPoint.y,  // 第一控制点
            rightPoint.x - controlPointOffset, rightPoint.y, // 第二控制点
            rightPoint.x, rightPoint.y                      // 终点
        );
        ctx.stroke();
    }
}

/**
 * 将PDF坐标转换为屏幕坐标
 * @param {Object} pdfCoords PDF坐标对象，包含pixelX, pixelY, pixelWidth, pixelHeight, pixelPageHeight属性
 * @param {Object} canvasRect 画布在屏幕上的位置和尺寸，包含left, top, width, height属性
 * @param {string} side 'left'或'right'，表示当前处理的是左侧还是右侧的坐标转换
 * @returns {Object} 转换后的屏幕坐标对象，包含x和y属性
 */
function convertPdfToScreenCoords(pdfCoords, canvasRect, side = 'left') {
    if (!pdfCoords || !canvasRect) return null;
    
    // 1. 将PDF坐标转换为像素坐标
    const x = pdfCoords.pixelX;
    // PDF坐标系y轴从底部开始，需要转换
    const y = pdfCoords.pixelPageHeight - pdfCoords.pixelY;
    
    // 2. 计算在屏幕上的实际位置
    const screenX = canvasRect.left + x;
    const screenY = canvasRect.top + y;
    
    // 3. 计算连接点位置
    let connectionPoint = {
        x: screenX,
        y: screenY + (pdfCoords.pixelHeight / 2) // 取文本框竖直中点
    };
    
    // 4. 根据左右两侧调整连接点的水平位置
    if (side === 'left') {
        connectionPoint.x = screenX + pdfCoords.pixelWidth + connectionOffset.value.left;
    } else {
        connectionPoint.x = screenX + connectionOffset.value.right;
    }
    
    return connectionPoint;
}

onMounted(async () => {
    let result = JSON.parse(localStorage.getItem('res'));
    pdf1Url.value = result.generatedFiles[0];
    pdf2Url.value = result.generatedFiles[1];

    diffList.value = result.differences; // 从结果中获取差异列表

    similarity.value = 100 - result.totalDifferences || 0; // 获取相似度


    const loadingTask = pdfjsLib.getDocument(pdf1Url.value)
    pdf1Instance = await loadingTask.promise
    pdf1TotalPages.value = pdf1Instance.numPages
    await loadAndRenderPdf(page1.value)
    // 右侧PDF
    const loadingTask2 = pdfjsLib.getDocument(pdf2Url.value)
    pdf2Instance = await loadingTask2.promise
    pdf2TotalPages.value = pdf2Instance.numPages
    await loadAndRenderPdf2(page2.value)
    // 高亮当前页面差异文本
})

</script>

<style scoped>
.page-arrow-btn {
    width: 28px;
    height: 28px;
    border: 1px solid #409eff;
    color: #409eff;
}

.compare-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.compare-header {
    min-height: 57px;
    height: 57px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 32px;
    background: #1B1E25;
    color: #fff;
}

.connection-controls {
    display: flex;
    align-items: center;
    margin: 0 10px;
}

.connection-control-title {
    font-size: 14px;
    margin-right: 8px;
    white-space: nowrap;
}

.connection-control-buttons {
    display: flex;
    gap: 5px;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 16px;
}

.similarity b {
    color: #409eff;
    font-size: 14px;
}

/* 主体区域：PDF+差异列表 */
.compare-main {
    display: flex;
    flex-direction: row;
    background: #131218;
    overflow: hidden;
}

/* PDF内容区 */
.pdf-compare-content {
    flex: 1;
    display: flex;
    gap: 16px;
    padding: 16px 32px;
    transition: width 0.2s;
    min-width: 700px;
}

.pdf-viewer {
    position: relative;
    flex: 1;
    min-width: 320px;
    background: #fff;
    border: 1.5px solid #2d2f37;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow: auto;
    /* max-height: 100%; */
    /* 或者 height: 100%; 具体看你的布局 */
}

.pdf-canvas {
    display: block;
    max-width: 100%;
    height: auto;
    margin: 0 auto;
}

/* 差异列表样式 */
.diff-list-panel {
    width: 20%;
    min-width: 260px;
    max-width: 400px;
    background: #23242a;
    color: #fff;
    padding: 24px 16px 0 16px;
    box-sizing: border-box;
    overflow-y: auto;
    border-left: 1px solid #222;
    display: flex;
    flex-direction: column;
}

.diff-list-title {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #fff;
}

.diff-item {
    background: #2d2f37;
    border-radius: 8px;
    padding: 16px 12px;
    margin-bottom: 18px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    cursor: pointer;
}

.diff-item:hover {
    border: 1.5px solid #409EFF;
}

.diff-title {
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 8px;
    color: #fff;
}

.diff-row {
    margin-bottom: 4px;
    font-size: 12px;
    word-break: break-all;
}

.diff-label {
    color: #aaa;
    margin-right: 4px;
}

.compare-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #1B1E25;
    border-top: 1px solid #1B1E25;
    height: 56px;
    padding: 0 32px;
    position: relative;
}

.footer-block {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 24px;
}

.footer-filename {
    color: #fff;
    font-weight: bold;
    font-size: 16px;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.footer-page {
    display: inline-flex;
    align-items: center;
    background: #23242a;
    border: 1.5px solid #444;
    padding: 2px 12px;
    font-size: 14px;
    font-weight: bold;
    min-width: 48px;
    justify-content: center;
    z-index: 2;
}

.page-current {
    color: #fff;
}

.page-sep,
.page-total {
    color: #aaa;
}

.similarity-badge {
    background: #2D2F37;
    padding: 2px 10px;
    border-radius: 4px;
    margin: 0 4px;
    display: inline-block;
}

.debug-active {
    background: #67c23a !important;
    border-color: #67c23a !important;
    color: #fff !important;
}

.pdf-canvas-full {
    width: 100%;
    height: 100%;
}

.footer-page-center {
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
